package com.leyou.gateway.filter;

import com.leyou.gateway.config.JwtProperties;
import com.leyou.task.PrivilegeTokenHolder;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * @author xiuer
 * @description 拦截zuul请求，将token放到请求头中
 * @create 2019/7/11 11:25
 */

@Component
@Slf4j
public class PrivilegeTokenFilter extends ZuulFilter {
    @Autowired
    private JwtProperties properties;

    @Autowired
    private PrivilegeTokenHolder tokenHolder;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * PRE_DECORATION_FILTER  前置装饰过滤器
     * 是Zuul默认的处理请求头的过滤器，我们放到这个之后执行
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        try {
            //获取上下文
            RequestContext ctx = RequestContext.getCurrentContext();
            //获取请求头
            ctx.addZuulRequestHeader(properties.getPrivilege().getHeaderName(), tokenHolder.getToken());
            log.info("【网关微服务】，设置头name {}，值 {}", properties.getPrivilege().getHeaderName(), tokenHolder.getToken());
            return null;
        } catch (Exception e) {
            log.error("【网关微服务】，设置头信息失败 。原因{}", e.getMessage(), e);
            throw new RuntimeException("网关微服务出现异常");
        }
    }
}
